package com.da.javatest.interview.session2;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

/**
 * @author chenlida
 * @date 2020/4/1 20:39
 * 如何设置线程池最大核数？
 * IO密集型：CPU核数*2 或者 CPU核数/(1-阻塞系数) 阻塞系数一般为0.8~0.9之间
 * CPU密集型：CPU核数 + 1
 * Runtime.getRuntime().availableProcessors() 获取核数
 */
public class Test22ThreadPool2 {
    /**
     * 模拟办理业务
     */
    public static void main(String[] args) {
        /// System.out.println(Runtime.getRuntime().availableProcessors());
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 10L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(3), new ThreadFactoryBuilder().setNameFormat("线程-%s").build(),
            new ThreadPoolExecutor.AbortPolicy());

        try {
            for (int i = 1; i <= 8; i++) {
                int fi = i;
                threadPoolExecutor.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + " 服务客户" + fi);
                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }
    }
}
